package haoyc.handler;

import haoyc.entity.Response;
import haoyc.entity.User;
import haoyc.server.RequestMessage;
import haoyc.utils.TheadPoolFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Memory
 * @version 1.0
 * @date 2021/11/23
 */
@Slf4j
public class LoginHandler extends ChannelInboundHandlerAdapter {

    private CountDownLatch waitLogin = new CountDownLatch(1);
    private AtomicBoolean loginStatus = new AtomicBoolean(false);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Scanner input = new Scanner(System.in);
        TheadPoolFactory.pool.execute(() -> {
            String local = null;
            try {
                local = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }

            System.out.println("请输入本机名称：");
            String name = input.next();
            User user = new User(name, local);
            // 创建包含登录信息的请求体
            ctx.writeAndFlush(user);

            try {
                waitLogin.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!loginStatus.get()) {
                // 登陆失败，关闭channel并返回
                ctx.channel().close();
                return;
            }

            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入控制端名称：");
            String desc = scanner.next();

            RequestMessage requestMessage = new RequestMessage(user.getName(), desc);

            while (true) {
                ctx.channel().writeAndFlush(requestMessage.sendMessages());
            }
        });
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            if (msg instanceof Response) {
                // 如果是登录响应信息
                Response message = (Response) msg;
                boolean isSuccess = message.isSuccess();
                // 登录成功，设置登陆标记
                if (isSuccess) {
                    loginStatus.set(true);
                    // 登陆后，唤醒登陆线程
                    waitLogin.countDown();
                }
                log.info("res is {}", msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.channelRead(ctx, msg);
    }

}
